﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Configuration;
using Android_Helper.android;
using Android_Helper.Utils;

namespace Android_Helper
{
    public partial class android_helper : Form
    {

        public android_helper()
        {
            InitializeComponent();
        }

        private void getViewList(List<string> ls, string layout)
        {
            Regex r = new Regex("<[^>]+>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            MatchCollection matches = r.Matches(layout);

            foreach(Match m in matches)
            {
                ls.Add(m.Value);
                Console.WriteLine(m.Value);
            }
        }

        private void androidLayout_Click(object sender, EventArgs e)
        {
            List<string> ls = new List<string>();
            List<string> ls_prelayout = new List<string>();
            getViewList(ls, rtb_layout.Text);
            getViewList(ls_prelayout, rtb_prelayout.Text);
            ls = ls.Except(ls_prelayout).ToList();
            rtb_result.Clear();
            StringBuilder sb_declare = new StringBuilder();
            StringBuilder sb_initView = new StringBuilder();
            StringBuilder sb_viewList = new StringBuilder();
            StringBuilder sb_idsuggest = new StringBuilder();
            foreach (string s in ls)
            {
                if (s.Trim().StartsWith("</"))
                {
                    continue;
                }
                string tag = getTag(s);

                tag = tag.Substring(tag.LastIndexOf(".")+1);
                string text = string.Empty;
                text = getTagText(s, text);
                string id = getTagId(s);
                if (!string.IsNullOrEmpty(id))
                {
                    if (!string.IsNullOrEmpty(text))
                    {
                        sb_declare.AppendLine(" //" + text);
                        sb_initView.AppendLine("        //" + text);
                    }
                    sb_declare.AppendLine("protected " + tag + " " + id.Replace("_", "") + ";");
                    sb_initView.AppendLine(id.Replace("_", "") + " = findViewById(R.id." + id + ");"); 
                    sb_viewList.AppendLine(id.Replace("_", ""));
                }
                if (!string.IsNullOrEmpty(text) && string.IsNullOrEmpty(id))
                {
                    id = getSimpleName(tag);
                    if (string.IsNullOrEmpty(id)) { id = tag; }
                    id = id.ToLower() + "_" + NameUtils.LowercaseUnderlineToCammle(NameUtils.HanZiToLowercaseUnderline(text));
                    id = id.Replace(":", "");
                    sb_idsuggest.AppendLine("tag: " + tag + "文本：" + text + "   id: " + id);
                }
            }

            rtb_result.AppendText("声名：\r\n");
            rtb_result.AppendText(sb_declare.ToString());
            rtb_result.AppendText("\r\n\r\n\r\n");

            rtb_result.AppendText("初始化：\r\n");
            rtb_result.AppendText(sb_initView.ToString());
            rtb_result.AppendText("\r\n\r\n\r\n");

            rtb_result.AppendText("view列表：\r\n");
            rtb_result.AppendText(sb_viewList.ToString());
            rtb_result.AppendText("\r\n\r\n\r\n");


            rtb_result.AppendText("views：\r\n");
            rtb_result.AppendText(sb_viewList.ToString().Replace("\r\n", " "));
            rtb_result.AppendText("\r\n\r\n\r\n");

            rtb_result.AppendText("建议的ID：\r\n");
            rtb_result.AppendText(sb_idsuggest.ToString());
            rtb_result.AppendText("\r\n\r\n\r\n");
        }

        private static string getTagId(string s)
        {
            string id = string.Empty;
            Regex rid = new Regex("android:id=\".+\"\\s", RegexOptions.IgnoreCase);
            Match mid = rid.Match(s);
            if (mid.Success)
            {
                //android:id="@+id/project_detail_deposit"
                id = mid.Value;
                id = id.Replace("\"", "");
                id = id.Replace("android:id=@+id/", "");
                id = id.Replace("\n", "");
            }

            return id;
        }

        private static string getTag(string s)
        {
            Regex rtag = new Regex("<[0-9A-Za-z\\.]*", RegexOptions.None);

            string tag = rtag.Match(s).Value.Replace("<", "");
            return tag;
        }

        private static string getTagText(string s, string text)
        {
            Regex rtext = new Regex("android:text=\".+\"\\s", RegexOptions.IgnoreCase);
            Match mtext = rtext.Match(s);
            if (mtext.Success)
            {
                text = mtext.Value;
                text = text.Replace("\"", "");
                text = text.Replace("android:text=", "");
                text = text.Replace("\n", "");
            }

            if (string.IsNullOrEmpty(text))
            {
                rtext = new Regex("android:hint=\".+\"\\s", RegexOptions.IgnoreCase);
                mtext = rtext.Match(s);
                if (mtext.Success)
                {
                    text = mtext.Value;
                    text = text.Replace("\"", "");
                    text = text.Replace("android:hint=", "");
                    text = text.Replace("\n", "");
                }
            }

            return text;
        }


        private string getSimpleName(string str)
        {
            string result = string.Empty;
            Regex rid = new Regex("[A-Z]", RegexOptions.None);
            foreach (Match mid in rid.Matches(str))
            {
                if (mid.Success)
                {
                    result += mid.Value;
                }
            }
            return result;
        }

        ///<summary> 
        ///返回*.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }
        ///<summary>  
        ///在*.exe.config文件中appSettings配置节增加一对键值对  
        ///</summary>  
        ///<param name="newKey"></param>  
        ///<param name="newValue"></param>  
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void iconRename_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            string folder = GetAppConfig("init_fbd");
            while (!Directory.Exists(folder))
            {
                folder = Directory.GetParent(folder).FullName;
            }
            fbd.SelectedPath = folder;
            if (fbd.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            folder = fbd.SelectedPath;
            UpdateAppConfig("init_fbd", folder);
            rtb_result.Clear();
            Dictionary<string, string> dir = new Dictionary<string, string>();

            foreach (string filename in Directory.GetFiles(folder, "*.png", SearchOption.AllDirectories))
            {
                string f = Path.GetFileNameWithoutExtension(filename);
                string enname = string.Empty;
                if (dir.ContainsKey(f))
                {
                    enname = dir[f];
                }
                else
                {
                    enname = "ico_"+NameUtils.HanZiToLowercaseUnderline(f);
                    dir.Add(f, enname);
                    rtb_result.AppendText("添加字典：" + f + "  ->  " + enname+"\r\n");
                }
                string destfile = Path.Combine(Path.GetDirectoryName(filename), enname + Path.GetExtension(filename));
                
                File.Move(filename, destfile);
            }
            rtb_result.AppendText("所有操作完成");
        }

        private void btnControlNameTranslation_Click(object sender, EventArgs e)
        {
            rtb_result.Text = NameUtils.HanZiToLowercaseUnderline(rtb_layout.Text);
        }

        private void btnDatabaseNameTranslation_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(rtb_layout.Text)) {
                return;
            }
            rtb_result.Text = NameUtils.HanZiToLowercaseUnderline(rtb_layout.Text);
        }

        private void btn_swagger_Click(object sender, EventArgs e)
        {
            rtb_result.Text = SwaggerUtils.getDefaultProcess(rtb_layout.Text);
        }

        private void btn_SwipeRefresh_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.AndroidSwipeRefreshLayoutAndCode.GetLayoutString();
            rtb_result.Text +="\n\n"+ android.AndroidSwipeRefreshLayoutAndCode.GetCodeString();
        }

        private void btn_androidseg_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.ThreeSegmentLayout.GetThreeSegment();
        }

        private void btnKeyValueView_Click(object sender, EventArgs e)
        {
            rtb_result.Clear();
            if (string.IsNullOrEmpty(rtb_layout.Text))
            {
                rtb_result.Text = android.ThreeSegmentLayout.GetKeyValueTextView("名称", "值", "KeyValue");
            }
            foreach (string line in rtb_layout.Lines)
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                string[] strs = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string key = strs[0];
                string value = strs.Length > 1 ? strs[1] : string.Empty;
                string enkey = Utils.xUtils.YouDaoTranslateTool(key);
                enkey = enkey.Replace(" ", "_");
                rtb_result.Text += android.ThreeSegmentLayout.GetKeyValueTextView(key, value, enkey);
            }
        }

        private void btnKeyValueWritable_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.ThreeSegmentLayout.GetKeyValueEditText();
        }

        private void btnRadioButtonTabSheetWithUnderline_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.RadioButton2Tab.getLayoutTabAndLine();
            rtb_result.Text += android.RadioButton2Tab.getCodeTabAndLine();
        }

        private void btnRadioButtonTabSheet_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.RadioButton2Tab.getLayoutTab();
            rtb_result.Text += android.RadioButton2Tab.getCodeTab();
        }

        private void MuiltySwagger_Click(object sender, EventArgs e)
        {
            rtb_result.Text = SwaggerUtils.GetSwaggerDao(rtb_layout.Text);
        }

        private void put2clear_Click(object sender, EventArgs e)
        {
            rtb_result.Text = android.AndroidCommonProcess.PutData2ClearData(rtb_layout.Text);
        }

        private string getConnectionString() {
            string ConnectionString = rtb_layout.Lines[0];
            if (string.IsNullOrEmpty(ConnectionString))
            {
                rtb_result.Text = "连接字符串中不能为空。";
                return string.Empty;
            }
            return ConnectionString;
        }

        private string getDBName()
        {
            string ConnectionString = getConnectionString();
            string dbName=string.Empty;
            Match match = Regex.Match(ConnectionString, @"database=(.*?);", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (match.Success)
            {
                dbName = match.Groups[1].Value;
            }

            if (string.IsNullOrEmpty(dbName))
            {
                rtb_result.Text = "连接字符串中找不到数据库名字。";
                return string.Empty;
            }
            return dbName;
        }

        private string getTableName()
        {
            string tableName = rtb_layout.Lines[1];
            tableName = tableName.Replace("tableName=", "").Trim();

            if (string.IsNullOrEmpty(tableName))
            {
                rtb_result.Text = "表名不能为空。";
                return string.Empty;
            }
            return tableName;
        }

        private bool CheckConnectionDB() {
            if (string.IsNullOrEmpty(rtb_layout.Text))
            {
                rtb_layout.AppendText("Database=stockdb;Data Source=192.168.1.210;User Id=root;Password=Passw0rd;pooling=false;CharSet=utf8;port=3306\n");
                rtb_layout.AppendText("tableName=bs_stock_info");
                return false;
            }
            
            if (rtb_layout.Lines.Length < 2)
            {
                rtb_result.Text = "连接字符串及表名配置不正确。正确配置方式可清空配置内容，再点击本功能查看";
                return false;
            }
            return true;
        }

        private void btnEntityToGolang_Click(object sender, EventArgs e)
        {
            if (!CheckConnectionDB()) {
                return;
            }
            string ConnectionString = getConnectionString();
            string dbName = getDBName();
            string tableName = getTableName();
            rtb_result.Text = golang.DescTableUtils.GoLangCRUD(ConnectionString, dbName, tableName);
        }

        private void btnEntityToAntdReact_Click(object sender, EventArgs e)
        {
            if (!CheckConnectionDB())
            {
                return;
            }
            string ConnectionString = getConnectionString();
            string dbName = getDBName();
            string tableName = getTableName();
            rtb_result.Text = antDegign.DescTableUtils.AntDesignReactCRUD(ConnectionString, dbName, tableName);
        }

        private void btnEntityPython_Click(object sender, EventArgs e)
        {
            if (!CheckConnectionDB())
            {
                return;
            }
            string ConnectionString = getConnectionString();
            string dbName = getDBName();
            string tableName = getTableName();
            rtb_result.Text = python.DescTableUtils.PythonCRUD(ConnectionString, dbName, tableName);
        }

        private void btnExcelPrintColumnTitle_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx";//过滤一下，只要表格格式的
            ofd.InitialDirectory = "c:\\";
            ofd.RestoreDirectory = true;
            ofd.FilterIndex = 1;
            ofd.AddExtension = true;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.ShowHelp = true;//是否显示帮助按钮
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Dictionary<int, string> dirs = Utils.ExcelUtils.getColumnTitle(ofd.FileName);
            
        }
    }
}
